/*
 *  Copyright 2011 yura.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package org.opu.vcforms.transform_t2d.util;

import java.io.StringReader;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
/**
 *
 * @author yura
 */
public class StringUtil extends XmlUtil{
    
    public byte[] rmWhiteSpace(String str){
        InputSource input = new InputSource(new StringReader(str));
        RmWhiteSpace handler = new RmWhiteSpace();

        try {
            sp.parse(input, handler);
        } catch (Exception ex) {
            throw new IllegalArgumentException("Bad parse output", ex);
        }

        return handler.accumulator.toString().getBytes();
    }

    class RmWhiteSpace extends DefaultHandler {
        private boolean lastTxt = false;
        StringBuilder accumulator = new StringBuilder()
                .append("<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\n");

        @Override
        public void characters(char[] buffer, int start, int length) {
            String str = new String(buffer, start, length);

            if (!lastTxt){
                str = str.trim();
            }

            append(str);
        }



        @Override
        public void startElement(String uri, String localName, String qName,
                Attributes atrbts) throws SAXException {
            openTag(uri, localName, qName, atrbts);

            final String[] arr = qName.split("\\:", 2);
            if (arr.length > 1 && TEXT_TAG.equals(arr[1])){
                lastTxt = true;
            }
        }

        @Override
        public void endElement(String uri, String localName, String qName)
                throws SAXException {
            closeTag(uri, localName, qName);
            final String[] arr = qName.split("\\:", 2);
            if (arr.length > 1 && TEXT_TAG.equals(arr[1])){
                lastTxt = false;
            }
        }

        @Override
        protected void append(CharSequence str) {
            accumulator.append(str);
        }
    }
}
